import Chest from "./Chest";

/**
 * 搬运工
 */

 export default class Carry extends Laya.Script {

    constructor() { super() }

    public sprite: Laya.Sprite

    public level: number = 1

    // 宝箱预制体
    /** @prop {name:chest,tips:"宝箱预制体",type:Prefab}*/
    private chest: Laya.Prefab;
    private chest_dom: Laya.Sprite

    private stop: boolean = false

    onEnable(): void {

        this.sprite = this.owner as Laya.Sprite

        this.setPosition()
        this.move()

    }

    onDisable(): void {
        Laya.Pool.recoverByClass(Carry)
    }

    // 移动并搬运
    private move(): void {
        let time = 2000 - this.level * 100
        Laya.Tween.to(this.sprite, {x: 450, y:this.sprite.y}, time, Laya.Ease.linearNone, new Laya.Handler(this, () => {
            // 搬运一个宝箱
            this.chest_dom = Laya.Pool.getItemByCreateFun("chest", this.chest.create, this.chest);
            this.owner.addChild(this.chest_dom);
            Laya.Tween.to(this.sprite, {x: 80 + Math.random() * 20, y: this.sprite.y}, time, Laya.Ease.linearNone, new Laya.Handler(this, () => {
                // 触发宝箱打开
                let c = this.chest_dom.getComponent(Chest)
                if (!this.stop) {
                    c.open()
                    // 金币增加动画
                    this.goldAni()
                    Laya.stage.event('goldAdd', this.level)
                    setTimeout(() => {
                        this.move()
                    }, 500)
                }
            }))
        }))
    }

    // 设置等级
    public setLevel(level: number): void {
        this.level = level
        this.sprite.loadImage('images/level_'+level+'.png')
    }

    // 设置位置
    private setPosition(): void {
        // 80 - 100 - 450
        this.sprite.x = 80 + Math.random() * 20
        // 125 - 175
        this.sprite.y = 125 + Math.random() * 50
    }

    // 金币增加动画
    private goldAni(): void {
        let T = new Laya.Text()
        T.text = '+' + this.level * 100
        T.color = '#e5f61f'
        T.fontSize = 24
        T.stroke = 2
        T.strokeColor = '#fb0e0a'
        this.owner.addChild(T)
        T.x = (this.sprite.width - T.width) / 2
        Laya.Tween.to(T, {y: T.y - 100}, 500, Laya.Ease.circOut, new Laya.Handler(this, () => {
            T.removeSelf()
        }))
    }

    // 停止动作
    public stopAction(): void {
        this.stop = true
    }

 }